/*
 * 修改记录:
 * 2016-11-21 ccf
 * 将业务处理交给专门的业务服务,本服务只负责数据转发
 * 
 * 2017-11-21 msx
 * 增加小局id
 *
 */

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var domain = require('domain');
var logger = require('./util/log').logger;
var liveTextDao = require('./dao/liveTextDao');
var matchMessageDao = require('./dao/matchMessageDao');
var server = require('./util/server');

app.get('/', function(req, res) {
    res.send('<h1>Welcome Realtime Server</h1>');
});

var EventEmitter = require('events').EventEmitter;
var domain = require('domain');
var d = domain.create();
d.run(function() {
    var a = new EventEmitter();
    var b = new EventEmitter();
    var da = domain.create();
    var db = domain.create();
    da.on('error', function() {
        console.log("domain error in da");
    });
    db.on('error', function() {
        console.log("domain error in db");
    });
    da.add(a);
    db.add(b);
    a.on('msg', function() {
        b.emit('error');
    });
    a.emit('msg');
});

//用于分布式时服务订阅，暂时不启用
// var zookeeper = require('node-zookeeper-client');
// var client = zookeeper.createClient('120.76.239.108:2181');
////console.log(client);
// function getData(client, path) {
// client.getData(
// path,
// function (event) {
// console.log('Got event: %s', event);
// getData(client, path);
// },
// function (error, data, stat) {
// if (error) {
// console.log('Error occurred when getting data: %s.', error);
// return;
// }

// console.log(
// 'Node: %s has data: %s, version: %d',
// path,
// data ? data.toString() : undefined,
// stat.version
// );
// }
// );
// }

//client.once('connected', function () {
//console.log('Connected to ZooKeeper.');
//  getData(client, '/UCMP/applications/tybpServer/v1.0/app');
//});

//client.connect();

logger.debug("collectTime=%s", 'log4js');

//在线用户
var onlineUsers = {};

var clientRegisterInfos = {}; //直播连接   以match_msg_id 作为key
var matchRegisterInfos = {}; //赛场连接  以match_msg_id 作为key

//当前在线人数
var onlineCount = 0;

//客户端和服务端建立连接
io.on('connection', function(socket) {
    //记录连接信息(IP等信息)
    var address = socket.handshake.address;
    logger.info("new connection from " + address);

    //监听新用户加入
    socket.on('login', function(obj) {
        //将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
        socket.name = obj.userid;

        //检查在线列表，如果不在里面就加入
        if(!onlineUsers.hasOwnProperty(obj.userid)) {
            onlineUsers[obj.userid] = obj.username;
            //在线人数+1
            onlineCount++;
        }
    });

    //裁判端 start

    /**
     * 连接比赛-注册比赛信息;
     *
     * @params registerInfo 注册信息
     * token:用户token;match_msg_id:比赛信息ID,match_msg_name:比赛信息名称
     */
    socket.on('registerMatch', function(registerInfoJson) {

        try {
            logger.info('invoke registerMatch:input=' + registerInfoJson);
            var registerInfo = JSON.parse(registerInfoJson);

            //校验注册信息
            if(!registerInfo || !registerInfo.token || !registerInfo.match_msg_id || !registerInfo.match_msg_name) {
                socket.emit('registerMatch', {
                    status: 203,
                    message: '注册失败,请求参数为空!'
                });
                logger.error('registerMatch failed!注册失败,请求参数为空!');
                return;
            }

            //用户token和比赛ID作为socket标识,用于后续消息调度;改
            socket.name = registerInfo.token + '-' + registerInfo.match_msg_id + '-' + registerInfo.smallmatch_id;
            logger.info('registerMatch: the match ' + registerInfo.match_msg_name + ' register success! socket.name:' + socket.name);

            //根据唯一标识缓存订阅信息;
            matchRegisterInfos[socket.name] = registerInfo; //缓存赛场注册信息
            logger.debug('registerMatch.matchRegisterInfos.current:' + JSON.stringify(matchRegisterInfos[socket.name]));

            //将裁判加入该比赛文字直播房间;改
            socket.join('textlive' + registerInfo.match_msg_id + '-' + registerInfo.smallmatch_id);
            logger.info('the judger join room...');

            //将该比赛设置为进行中.改
            logger.info('registerMatch:update game_status...');
            server.sendPostData({
                url: '/App/Live/match_start',
                content: {
                    'match_msg_id-eq': registerInfo.match_msg_id,
                    'smallmatch_id-eq': registerInfo.smallmatch_id,
                    'token': registerInfo.token
                }
            }, function(err, result) {
                if(!err) {
                    logger.info('live:' + socket.name + ' match_message game_status update success!');
                }
                logger.debug('registerMatch:result=' + result);
                socket.emit('registerMatch', result);
            });
        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('registerMatch', failjsonData);
            logger.error(socket.name + 'registerMatch error:' + e);
        }
    });

    /**
     * 开始比赛
     * @params obj  实际开始时间
     * game_time 进行时间
     */
    socket.on('begin', function(objJson) {

        try {
            logger.info('begin:input=' + objJson);

            //var obj=JSON.parse(objJson);
            logger.debug("invoke begin...");
            //根据当前连接获取比赛信息
            try {
                var registerInfo = matchRegisterInfos[socket.name];
                // logger.debug('registerInfo=' + registerInfo);
                var match_msg_id = registerInfo.match_msg_id;
                var match_msg_name = registerInfo.match_msg_name;
                // 增加小局id-莫松兴
                var smallmatch_id = registerInfo.smallmatch_id;

                //通知查看该比赛的用户比赛即将开始
                logger.info('begin:' + match_msg_name + ' is begin,and notify clients');
                // 增加小局id-莫松兴
                io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('textMessage', match_msg_name + ',开始了!');

                var successResult = {
                    status: 100,
                    message: '操作成功!'
                };
                var successjsonData = JSON.stringify(successResult) + '';
                socket.emit('begin', successjsonData);
            } catch(ee) {
                logger.error('begin error:' + ee);
            }
        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('begin', failjsonData);
            logger.error(socket.name + 'begin error:' + e);
        }

    });

    /**
     * 比分直播-设置比分
     * 客户端实时上传
     *比赛直播开始后,计分员针对比赛情况进行实时计分,
     *计分信息包括:token,得分时间,比赛ID,得分队伍ID,得分队伍名称，得分人ID,得分人姓名，得分行为,得分,
     *计分后及时广播给其他用户进行文字直播
     *同时将得分信息持久化到数据库.
     *参数格式如下:
     *game_time
     *current_stage
     *team_id
     *team_name
     *user_id
     *user_name
     *current_score
     *text
     *action_id
     *action_name
     *time
     */
    socket.on('uploadMatchData', function(objJson) {

        try {
            logger.info('invoke uploadMatchData:input=' + objJson);
            var obj = JSON.parse(objJson);

            //根据当前连接获取比赛信息
            logger.debug('uploadMatchData:matchRegisterInfos:' + JSON.stringify(matchRegisterInfos));
            if(matchRegisterInfos) {
                logger.debug('uploadMatchData.matchRegisterInfos.length:' + JSON.stringify(matchRegisterInfos).length);
            }
            var registerInfo = matchRegisterInfos[socket.name];
            logger.debug('uploadMatchData.registerInfo:' + JSON.stringify(registerInfo));

            var token = registerInfo.token;
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            // 增加小局id
            var smallmatch_id = registerInfo.smallmatch_id;
            obj.match_msg_id = match_msg_id;
            // 增加小局id
            obj.smallmatch_id = smallmatch_id;
            obj.token = token;

            var liveInfo = {};
            liveInfo.token = obj.token;
            liveInfo.match_msg_id = obj.match_msg_id;
            liveInfo.game_time = obj.game_time;
            liveInfo.current_stage = obj.current_stage;
            liveInfo.team_id = obj.team_id;
            liveInfo.user_id = obj.user_id;
            liveInfo.user_name = obj.user_name;
            liveInfo.current_score = obj.current_score;
            liveInfo.text = obj.text;
            liveInfo.action_id = obj.action_id;
            liveInfo.time = obj.time;
            liveInfo.team_name = obj.team_name;
            // 增加小局id-莫松兴
            liveInfo.smallmatch_id = obj.smallmatch_id;

            server.sendPostData({
                url: '/App/Live/add_live_text',
                content: liveInfo
            }, function(err, result) {
                logger.info('live_id:' + result);
                var resultObj = JSON.parse(result);
                //更新用户比分
                logger.debug('update user score');
                server.sendPostData({
                    url: '/App/Live/save_score',
                    content: {
                        token: token,
                        'live_id-eq': resultObj.data.live_id
                    }
                });
                // 增加小局id-莫松兴
                logger.info(match_msg_id + '-' + smallmatch_id + ' uploadMatchData and notify clients getLatestScore event');

                obj.live_id=resultObj.data.live_id;
           var getLatestScoreResult = {
                status : 100,
                message : '操作成功!',
                data : obj
            };
            var getLatestScoreResultJson = JSON.stringify(getLatestScoreResult) + '';
            
                // 增加小局id-莫松兴
                io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getLatestScore', getLatestScoreResultJson);

                socket.emit('uploadMatchData', result);

                //同时更新比分排行版

                server.sendPostData({
                    url: '/App/Live/Billboard',
                    content: {
                        token: token,
                        'match_msg_id-eq': match_msg_id,
                        // 增加小局id-莫松兴
                        'smallmatch_id-eq': smallmatch_id,
                        'field': 'list',
                        'cur_page': 1,
                        'page_size': 10000
                    }
                }, function(error, result) {
                    var resultObj=JSON.parse(result);
                    //resultObj.data=resultObj.data.list;
                    for (var prop in resultObj.data) 
                    { 
                        resultObj.data[prop]=resultObj.data[prop].list;
                    } 
                    result=JSON.stringify(resultObj);
                    logger.debug(result);
                    // 增加小局id-莫松兴
                    io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getLatestRange', result);
                });

            });
        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('uploadMatchData', failjsonData);
            logger.error(socket.name + 'uploadMatchData error:' + e);
        }
    });

    /**
     * 根据直播ID删除比分
     *参数格式如下:
     *live_id
     */
    socket.on('removeMatchData', function(objJson) {

        try {
            logger.info('invoke removeMatchData:input=' + objJson);
            var obj = JSON.parse(objJson);

            var registerInfo = matchRegisterInfos[socket.name];
            logger.debug('uploadMatchData.registerInfo:' + registerInfo);

            var token = registerInfo.token;
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;
            obj.token = token;

            server.sendPostData({
                url: '/App/Live/delete_score',
                content: obj
            }, function(err, result) {
                logger.info('live_id:' + result);

                //同时更新比分排行版

                server.sendPostData({
                    url: '/App/Live/Billboard',
                    content: {
                        token: token,
                        'match_msg_id-eq': match_msg_id,
                        // 增加小局id-莫松兴
                        'smallmatch_id-eq': smallmatch_id,
                        'field': 'list',
                        'cur_page': 1,
                        'page_size': 10000
                    }
                }, function(error, result) {
                    var resultObj=JSON.parse(result);
                    for (var prop in resultObj.data) 
                    { 
                        resultObj.data[prop]=resultObj.data[prop].list;
                    } 
                    result=JSON.stringify(resultObj);
                    logger.debug(result);
                    // 增加小局id-莫松兴
                    io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getLatestRange', result);
                    
                    //更新直播历史记录
                    server.sendPostData({
                        url: '/App/Live/get_live_text_list',
                        content: {
                            'token':token,
                            'match_msg_id-eq': match_msg_id,
                            // 增加小局id-莫松兴
                            'smallmatch_id-eq': smallmatch_id,
                            'field':'list',
                            'cur_page':1,
                            'page_size':10000
                        }
                    }, function(error, historyresult) {
                        //前端没有分页,中间处理
                        var historyresultObj=JSON.parse(historyresult);
                        historyresultObj.data=historyresultObj.data.list;
                        historyresultObj.data.list=[];
                        historyresult=JSON.stringify(historyresultObj);
                        logger.debug(historyresult);
                        // 增加小局id-莫松兴
                        io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getlivehistory', historyresult);
                    });
                });
                
                var successResult = {
                status: 100,
                message: '删除比分成功!'
            };
            var successjsonData = JSON.stringify(successResult) + '';
            socket.emit('removeMatchData', successjsonData);
            });
        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('removeMatchData', failjsonData);
            logger.error(socket.name + 'removeMatchData error:' + e);
        }
    });

    /**
     *缓存比赛状态,便于手机异常退出时缓存比赛状态
     */
    socket.on('updateMatchMsgStatus', function(objJson) {

        logger.debug('invoke updateMatchMsgStatus,input=' + objJson);
        try {
            var obj = JSON.parse(objJson);
            var registerInfo = matchRegisterInfos[socket.name];
            logger.debug('uploadMatchData.registerInfo:' + registerInfo);

            var token = registerInfo.token;
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            logger.info('starting update_match_msg_status');
            
            
           server.sendPostData({
                    url: '/App/Live/add_live_last_status',
                    content: {
                        token: token,
                        'match_msg_id': match_msg_id,
                        // 增加小局id-莫松兴
                        'smallmatch_id': smallmatch_id,
                        'all_seconds': obj.all_seconds
                    }
                }, function(error, result) {
                    logger.debug(result);
                    io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('updateMatchMsgStatus', result);
                });
        } catch(ex) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('updateMatchMsgStatus', failjsonData);
            logger.error('updateMatchMsgStatus error:' + ex);
        }
    });

    /**
     * 暂停比赛
     */
    socket.on('pause', function(objJson) {

        try {
            logger.info('invoke pause:input=' + objJson);
            //var obj=JSON.parse(objJson);
            var registerInfo = matchRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            // 增加小局id-莫松兴
            logger.info('pause:' + match_msg_id + '-' + smallmatch_id + ' pause and notify clients pause event');
            // 增加小局id-莫松兴
            io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('pause', objJson);

            var successResult = {
                status: 100,
                message: '操作成功!'
            };
            var successjsonData = JSON.stringify(successResult) + '';
            socket.emit('pause', successjsonData);

        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('pause', failjsonData);
            logger.error(socket.name + 'pause error:' + e);
        }
    });

    /**
     * 结束比赛
     */
    socket.on('end', function(objJson) {

        try {
            logger.info('invoke end:input=' + objJson);
            //var obj=JSON.parse(objJson);
            var registerInfo = matchRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            var token = registerInfo.token;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            logger.info(match_msg_id + ' end and notify clients end event');

            server.sendPostData({
                url: '/App/Live/match_end',
                content: {
                    'token':token,
                    'match_msg_id-eq': match_msg_id,
                    'smallmatch_id-eq': smallmatch_id
                }
            }, function(error, result) {
                logger.debug(result);
                io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('end', result);
            });
            logger.info('end:starting update game_status to 0');

            //io.to('textlive' + match_msg_id).emit('end', objJson);

            // var successResult = {
                // status: 100,
                // message: '操作成功!'
            // };
            // var successjsonData = JSON.stringify(successResult) + '';
            // socket.emit('end', successjsonData);

        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('end', failjsonData);
            logger.error(socket.name + 'end error:' + e);
        }
    });
    
     /**
     * 裁判通信
     */
    socket.on('adminNotify', function(objJson) {

        try {
            logger.info('invoke adminNotify:input=' + objJson);
            var registerInfo = matchRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            logger.info(match_msg_id + '-' + smallmatch_id + ' adminNotify and notify clients end event');

             io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('adminNotify', objJson);

        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('end', failjsonData);
            logger.error(socket.name + 'end error:' + e);
        }
    });

    //裁判端 end

    //用户端 start
    /**
     * 注册-客户端加入赛事直播
     * 注册信息
     *@params registerInfo:
     * token: 用户token
     * match_msg_id:赛事信息标识
     * smallmatch_id:小局信息标识
     * fields: 订阅字段信息 逗号"," 分割，"*" 代表所有字段;
     */
    socket.on('register', function(registerInfoJson) {

        try {
            logger.info('invoke register:input=' + registerInfoJson);
            var registerInfo = JSON.parse(registerInfoJson);
            //将用户加入该比赛文字直播房间
            socket.join('textlive' + registerInfo.match_msg_id + '-' + registerInfo.smallmatch_id);

            //用户token和比赛ID作为socket标识,用于后续消息调度;
            socket.name = registerInfo.token + '-' + registerInfo.match_msg_id + '-' + registerInfo.smallmatch_id;
            ////根据唯一标识缓存订阅信息;
            clientRegisterInfos[socket.name] = registerInfo; //缓存注册信息

            logger.info(registerInfo.token + ' join room ' + 'textlive' + registerInfo.match_msg_id + '-' + registerInfo.smallmatch_id);

            var successResult = {
                status: 100,
                message: '操作成功!'
            };
            var successjsonData = JSON.stringify(successResult) + '';
            socket.emit('register', successjsonData);
        } catch(e) {
            var failResult = {
                status: 301,
                message: '系统错误!'
            };
            var failjsonData = JSON.stringify(failResult) + '';
            socket.emit('register', failjsonData);
            logger.error(socket.name + 'register error:' + e);
        }
    });

    /**
     * 获取当前点之前的直播记录(历史记录)
     * 参数为
     */
    socket.on('getlivehistory', function(objJson) {

        try {
            logger.info('invoke getlivehistory:input=' + objJson);
            //var obj=JSON.parse(objJson);
            var registerInfo = JSON.parse(objJson);
            // var registerInfo = clientRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            var token = registerInfo.token;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            //查询历史记录
            server.sendPostData({
                url: '/App/Live/get_live_text_list',
                content: {
                    'token':token,
                    'match_msg_id-eq': match_msg_id,
                    'smallmatch_id-eq': smallmatch_id,
                    'field':'list',
                    'cur_page':1,
                    'page_size':10000
                }
            }, function(error, result) {
                //前端没有分页,中间处理
                var resultObj=JSON.parse(result);
                resultObj.data=resultObj.data.list;
                resultObj.data.list=[];
                result=JSON.stringify(resultObj);
                logger.debug(result);
                io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getlivehistory', result);
            });
        } catch(e) {
            socket.emit('getlivehistory', {
                status: 301,
                message: '系统错误!'
            });
            logger.error(socket.name + 'getlivehistory error:' + e);
        }
    });

    /**
     *获取历史的比分数据
     */
    socket.on('getrangehistory', function(objJson) {

        try {
            logger.info('invoke getrangehistory:input=' + objJson);
            //var obj=JSON.parse(objJson);
            var registerInfo = clientRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            var token = registerInfo.token;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            //查询历史记录
            logger.info('getrangehistory:starting to select_user_range..');
            server.sendPostData({
                    url: '/App/Live/Billboard',
                    content: {
                        token: token,
                        'match_msg_id-eq': match_msg_id,
                        'smallmatch_id-eq': smallmatch_id,
                        'field': 'list',
                        'cur_page': 1,
                        'page_size': 10000
                    }
                }, function(error, result) {
                    var resultObj=JSON.parse(result);
                    //resultObj.data=resultObj.data.list;
                    for (var prop in resultObj.data) 
                    { 
                        resultObj.data[prop]=resultObj.data[prop].list;
                        //遍历所有用户
                        // for(var i=0;i<resultObj.data[prop].length;i++){
                            // if(resultObj.data[prop][i].actions&&resultObj.data[prop][i].actions.length>0){
                                // var action=resultObj.data[prop][i].actions[0];
                                // for(var ac in action){
                                   // var v= action[ac];
                                   // for(var sv in v){
                                       // v[sv]=v[sv]+'';
                                   // }
                                // }
                            // resultObj.data[prop][i].actions=action;
                            // }
                        // }
                    } 
                    result=JSON.stringify(resultObj);
                    logger.debug(result);
                    io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('getrangehistory', result);
                });
        } catch(e) {
            socket.emit('getrangehistory', {
                status: 301,
                message: '系统错误!'
            });
            logger.error(socket.name + 'getrangehistory error:' + e);
        }
    });

    //用户端 end

    /**
     * 监听连接断开
     * 裁判端失去连接时，通知用户端;
     */
    socket.on('disconnect', function() {
        logger.debug("invoke disconnect,socket.name" + socket.name);
        //判断是否为裁判端
        //根据当前连接获取比赛信息
        var info = matchRegisterInfos[socket.name];
        if(info) {

            var registerInfo = matchRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            var match_msg_name = registerInfo.match_msg_name;
            // 增加小局id-莫松兴
            var smallmatch_id = registerInfo.smallmatch_id;

            io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('matchDisconnect', match_msg_name + ',信号不正常!');
        }

        //将退出的用户从在线列表中删除
        if(clientRegisterInfos.hasOwnProperty(socket.name)) {
            //退出用户的信息
            var obj = {
                userid: socket.name,
                username: clientRegisterInfos[socket.name]
            };

            //删除
            delete clientRegisterInfos[socket.name];

            logger.info('the client:' + obj.userid + ' disconnect');
        }
        if(matchRegisterInfos.hasOwnProperty(socket.name)) {
            logger.info('the match room disconnect');
        }
    });

    /**
     * 监听用户发布聊天信息，并将聊天信息广播其他用户
     */
    socket.on('message', function(obj) {

        try {
            logger.debug("invoke message...");
            logger.debug(obj);
            var registerInfo = clientRegisterInfos[socket.name];
            var match_msg_id = registerInfo.match_msg_id;
            //向所有客户端广播发布的消息

            io.to('textlive' + match_msg_id + '-' + smallmatch_id).emit('message', {
                userName: registerInfo.userName,
                'message': obj
            });
            console.log(obj.username + '说：' + obj.content);
        } catch(e) {
            socket.emit('message', {
                status: 301,
                message: '系统错误!'
            });
            logger.error(socket.name + 'getlivehistory error:' + e);
        }
    });

    /**
     * 测试接口
     */
    socket.on('test', function(obj) {

        try {
            logger.debug("invoke test...");
            socket.emit('test', 'Hello,World!');
            //console.log();
        } catch(e) {
            logger.error(socket.name + 'test error:' + e);
        }
    });
});

http.listen(3501, function() {
    console.log('listening on *:3501');
});

app.post('/login', function(req, res) {
    console.info(res.token);
    var user_name = req.body.user;
    var password = req.body.password;
    console.log("User name = " + user_name + ", password is " + password);
    res.end("yes");
});